﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using BusinessLibrary;
using MMSWebsite.Business;
using MMSWebsite.DataAccessManagement;
using MMSWebsite.DataAccessManagement.AssetManagement;
using MMSWebsite.HtmlHepler;
using MMSWebsite.Models.Asset;
using MMSWebsite.Models;

namespace MMSWebsite.Controllers
{
    public class AssetController : Controller
    {
        MMSEntities _entities = new MMSEntities();
        readonly AssetProvider _ap = new AssetProvider();
        CustomerAccessProvider _cap = new CustomerAccessProvider();
        MasterDataAccessProvider _mdap = new MasterDataAccessProvider();
        EmployeeAccessProvider _eap = new EmployeeAccessProvider();

        
        public ActionResult Index(int cusId)
        {
            var assets = _ap.GetAssetsByCusid(cusId);
            return View(assets);
        }

        public ActionResult GetAssetResult(int cusId)
        {
            var assets = _ap.GetAssetsResultByCusid(cusId);
            return View("IndexResult", assets);
        }

        public ActionResult Create(int cusId)
        {  
            SetViewBagData();

            //create new asset for specific Customer
            Asset asset = new Asset();
            asset.Customer = _cap.GetCusById(cusId);
            return View(asset);
        }

        [HttpPost]
        public ActionResult Create(Asset asset)
        {
            //asset chỉ nhận đc value cua assettype, do đó select theo value để lấy toàn bộ giá trị ra
            //gán vào asset
            var masterAssetType = _mdap.GetMDByValue(asset.AssetType.value);
            asset.AssetType = masterAssetType[0];

            //thực hiện insert new - chua valuate, loan, rate
            _ap.AddAsset(asset);

            return RedirectToAction("Details", "CusMgn", new {id = asset.Customer.Id});
        }

        public void SetViewBagData()
        {
            //Get list Value of Asset Type in MasterData
            ViewBag.AssetTypes = _mdap.GetMDByCode(Constants.STR_ASSET).Select(x => x.value).Distinct();
        }

        /// <summary>
        /// Direct To Edit View With Relevant Asset Id
        /// </summary>
        /// <param name="assetId">Asset Id</param>
        /// <returns></returns>
        public ActionResult Edit(int assetId)
        {
            Asset asset = null;
            try
            {
                SetViewBagData();

                //Edit asset relevant to asset id
                asset = _ap.GetAssetById(assetId);
                
                //asset.Customer = _cap.GetCusById();
                return View(asset);
            }
            catch (Exception ex)
            {
                Models.HandleErrorInfo hei = new Models.HandleErrorInfo(ex, "Asset", "Edit");
                return View("Error", hei);
            }
        }

        /// <summary>
        /// Edit Asset Relevant To Customer
        /// </summary>
        /// <param name="asset">Asset</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(Asset asset)
        {
            try
            {
                //asset chỉ nhận đc value cua assettype, do đó select theo value để lấy toàn bộ giá trị ra
                //gán vào asset
                var masterAssetType = _mdap.GetMDByValue(asset.AssetType.value);
                asset.AssetType = masterAssetType[0];

                //thực hiện edit asset- chua valuate, loan, rate with role tuong ung
                // Get employee info loging in
                EmployeeViewModel evm = _eap.GetEmployeeByCode(User.Identity.Name);
                if (evm == null || (evm != null && evm.Roles == null))
                {
                    return RedirectToAction("Details", "CusMgn", new { id = asset.Customer.Id });
                }
                
                
                _ap.EditAsset(asset, evm);

                return RedirectToAction("Details", "CusMgn", new { id = asset.Customer.Id });
            }
            catch (Exception ex)
            {
                Models.HandleErrorInfo hei = new Models.HandleErrorInfo(ex, "Asset", "Edit");
                return View("Error", hei);
            }
        }

        #region FV finished all assets
        public ActionResult FVFinish(int cusId)
        {
            var customer = _entities.MMS_CUSTOMERs.FirstOrDefault(x => x.Id == cusId);
            if (customer != null)
            {
                customer.MMS_EMP_CUS_CTRL.Last().finishedDate = DateTime.Now;
                _entities.SaveChanges();
            }

            return RedirectToAction("FvCustomers", "CusMgn");
        }

        #endregion

        public ActionResult ConfirmLoan(int assetId)
        {
            try
            {
                _ap.UpdateStatusCase(assetId, Constants.STR_TYPE_STATUS_ACCEPTED);
                if (Roles.Provider.IsUserInRole(User.Identity.Name, Constants.FV_ROLE))
                    return RedirectToAction("FVCustomers", "CusMgn");
                else return RedirectToAction("StoreResult", "CusMgn");
            }
            catch (Exception)
            {
                throw;
            }
        }

        public ActionResult RefuseLoan(int assetId)
        {
            try
            {
                _ap.UpdateStatusCase(assetId, Constants.STR_TYPE_STATUS_REFUSED);
                if (Roles.Provider.IsUserInRole(User.Identity.Name, Constants.FV_ROLE))
                    return RedirectToAction("FVCustomers", "CusMgn");
                else return RedirectToAction("StoreResult", "CusMgn");
            }
            catch (Exception)
            {
                throw;
            }
        }

        public ActionResult SendEmailFinishLoan(int fvid, int cusid)
        {
            var fv = _eap.GetEmployeeById(fvid);
            var cus = _cap.GetCusById(cusid);
            var reviewer = _eap.GetEmployeeByCode(User.Identity.Name);
            WebMailHelper.SendFinishLoan(fv, reviewer, cus);
            return RedirectToAction("Checking", "CusMgn");
        }
    }

}